import './style.css';
import MapCtrl from './components/control/MapCtrl';
import RoadCondHandler from './components/control/RoadCondHandler';
import RoadWeatherHandler from './components/control/RoadWeatherHandler';
import TemperatureHandler from './components/control/TemperatureHandler';
import WindHandler from './components/control/WindHandler';
import RainHandler from './components/control/RainHandler';
import CongestionHandler from './components/control/CongestionHandler';
import IncidentHandler from './components/control/IncidentHandler';
import RhHandler from './components/control/RhHandler';
import OdHandler from './components/control/OdHandler';
import Legend from './components/Legend/Legend';
import Popup from './components/Popup/Popup';
import TimeLineHandler from './components/control/TimeLineHandler';
import InfoBarList from './components/InfoBarList/InfoBarList';

let map = null;
let pid = -1;
const backgroundId = 'e9424af07d8242adb4fa49abe40544b4';
const topId = 'road-highlight';
let popup = null;
let legend = null;
let legendArr = [];
let legendArrObj = null;
let popupBox = null;
let roadWeatherChart = null;
let isSignIn = false;
let isBoxShow = true;

const showStatus = {
    roadCond: true,//路况
    incident: true,//事件
    temperature: false,//温度
    wind: false,//风力
    seeing: false,//能见度
    rain: false,//降水量
    od: false,//人流分析
};

let roadCondHandler = null;
let roadWeatherHandler = null;
let congestionHandler = null;
let incidentHandler = null;
let temperatureHandler = null;
let windHandler = null;
let rainHandler = null;
let rhHandler = null;
let odHandler = null;
let timeLineHandler = null;

$(document).ready(function () {
    map = MapCtrl.initMap();
    popup = new minemap.Popup({
        offset: [0, -5]
    }).addTo(map);

    roadCondHandler = new RoadCondHandler();
    roadWeatherHandler = new RoadWeatherHandler();
    congestionHandler = new CongestionHandler();
    incidentHandler = new IncidentHandler();
    temperatureHandler = new TemperatureHandler();
    windHandler = new WindHandler();
    rainHandler = new RainHandler();
    rhHandler = new RhHandler();
    odHandler = new OdHandler();
    legendArrObj = {
        roadCond: roadCondHandler.getLegendObj(),
        temperature: temperatureHandler.getLegendObj(),
        rh: rhHandler.getLegendObj(),
        rain: rainHandler.getLegendObj()
    }

    legend = new Legend('legend', roadCondHandler.getLegendObj());
    legendArr.push('roadCond');

    popupBox = new Popup(popup, map);

    timeLineHandler = new TimeLineHandler((value) => {
        rainHandler.setValue(map, value);
        odHandler.setValue(map, value);
    }, (valueNum) => {
        if (showStatus.roadCond) roadCondHandler.setValueNum(map, valueNum);
        temperatureHandler.setValueNum(map, valueNum);
        rhHandler.setValueNum(map, valueNum);
        windHandler.setValueNum(map, valueNum);
        congestionHandler.setValueNum(map, valueNum);
    });

    map.on('load', function () {
        onMapLoadAction();
    });
    map.on('click', function (e) {
        onMapClickAction(e);
    });
    map.on('mousemove', function (e) {
        onMapMouseMoveAction(e);
    });

    initButtonAction();

    initSignIn();
    initBoxControlButton();
});

function onMapLoadAction() {
    $('#loading').css('display', 'none');
    MapCtrl.initWeatherSource(map);
    MapCtrl.initWeatherLayers(map, backgroundId, pid);

    incidentHandler.loadData(map, true);
    const center = map.getCenter();
    roadWeatherHandler.loadData(center.lng, center.lat, true);
    congestionHandler.loadData(map, true);
    roadCondHandler.init(map);
    roadCondHandler.showRoadCondLayers(map, topId);

    temperatureHandler.loadData(map, true);
    // windHandler.loadData(map, false);
    windHandler.initWindVelocity(map, false);
    // rainHandler.loadData(map, false);
    odHandler.init(map);

    // minemap.util.getJSON('../data/xianTem.json', function (error, data) {
    //     const dataArr = data ? data.data.rows[0].features || [] : [];
    //     const infoObj = {
    //         "color1": "#FEC819",
    //         "color2": "#00C0CE",
    //         "unit": "温度（℃）",
    //         "array": [],
    //         callback: (coordinate) => {
    //             map.flyTo({
    //                 center: coordinate,
    //                 zoom: 13
    //             });
    //         }
    //     };
    //     dataArr.map((item) => {
    //         infoObj.array.push({
    //             "name": item.properties.name,
    //             "value": item.properties.tem,
    //             "coordinate": item.geometry.coordinates[Math.ceil(item.geometry.coordinates.length / 2)]
    //         })
    //     });
    //     roadWeatherChart = new InfoBarList('road-weather-chart', infoObj || {}, 37);
    // });
}

function onMapClickAction(e) {
    let layerIds = [];
    if (showStatus.incident && map.getLayer('5a3ea454892d4824b622cdabb48950a2')) {
        layerIds.push('5a3ea454892d4824b622cdabb48950a2');
    }
    if (map.getLayer('road-speed-symbol')) {
        layerIds.push('road-speed-symbol');
    }
    let features = map.queryRenderedFeatures(e.point, {layers: layerIds});
    let style = map.getCanvas().style;
    if (features && features.length > 0) {
        style.cursor = 'pointer';
    } else {
        style.cursor = '';
    }

    if (features && features.length > 0) {
        const f = features[0];
        const properties = f.properties;
        if (f.layer.id == 'road-speed-symbol') {
            map.flyTo({
                center: f.geometry.coordinates
            });
            popupBox.setData(properties, e);
            if (!isSignIn) {
                $('#sign-in-mask').css('display', 'block');
                popupBox.hidden();
            }
        }
        if (f.layer.id == '5a3ea454892d4824b622cdabb48950a2' && showStatus.incident) {
            incidentHandler.onMouseClickHandler(map, f);
        } else {
            incidentHandler.onMouseClickHandler(map, null);
        }
    }
}

function onMapMouseMoveAction(e) {
    let feature = null;
    let layerIds = [];
    if (showStatus.incident && map.getLayer('5a3ea454892d4824b622cdabb48950a2')) {
        layerIds.push('5a3ea454892d4824b622cdabb48950a2');
    }
    if (map.getLayer('road-speed-symbol')) {
        layerIds.push('road-speed-symbol');
    }
    const features = map.queryRenderedFeatures(e.point, {layers: layerIds});
    if (features && features.length > 0) {
        feature = features[0];
    }
    let style = map.getCanvas().style;
    if (feature) {
        style.cursor = 'pointer';
        if (feature.layer.id == '5a3ea454892d4824b622cdabb48950a2' && showStatus.incident) {
            incidentHandler.onMouseMoveHandler(map, feature);
        } else {
            incidentHandler.onMouseMoveHandler(map, null);
        }
    } else {
        style.cursor = '';
        incidentHandler.onMouseMoveHandler(map, null);
    }
}

function initButtonAction() {
    initRoadCondButtonAction();
    initIncidentButtonAction();
    initRainButtonAction();
    initRhButtonAction();
    initTemButtonAction();
    initWinsButtonAction();
    initOdButtonAction();
}

function initRoadCondButtonAction() {
    const roadConditionButton = document.getElementById('road-condition-button');
    roadConditionButton.addEventListener('click', () => {
        showStatus.roadCond = !showStatus.roadCond;
        roadConditionButton.className = showStatus.roadCond ? 'weather-switch-selected' : 'weather-switch-not-selected';

        toggleButtonAction();
        if (showStatus.roadCond) {
            roadCondHandler.showRoadCondLayers(map, topId);
            // legend.setData(roadCondHandler.getLegendObj());
            legendArr.push('roadCond');
            updateLegend();
        } else {
            roadCondHandler.hideRoadCondLayers(map, backgroundId);
            legendArr.splice(legendArr.indexOf('roadCond'), 1);
            updateLegend();
        }
    });
}

function initIncidentButtonAction() {
    const incidentButton = document.getElementById('incident-button');
    incidentButton.addEventListener('click', () => {
        showStatus.incident = !showStatus.incident;
        incidentButton.className = showStatus.incident ? 'weather-switch-selected' : 'weather-switch-not-selected';

        toggleButtonAction();
        if (showStatus.incident) {
            incidentHandler.setVisible(map);
        } else {
            incidentHandler.setUnvisible(map);
        }
    });
}

function initTemButtonAction() {
    const temButton = document.getElementById('tem-button');
    temButton.addEventListener('click', () => {
        showStatus.temperature = !showStatus.temperature;
        temButton.className = showStatus.temperature ? 'weather-switch-selected' : 'weather-switch-not-selected';

        toggleButtonAction();
        if (showStatus.temperature) {
            // map.setLayoutProperty('tem', 'visibility', 'visible');
            temperatureHandler.setVisible(map);
            // legend.setData(temperatureHandler.getLegendObj());
            // temperatureHandler.updateChart();
            legendArr.push('temperature');
            updateLegend();
        } else {
            // map.setLayoutProperty('tem', 'visibility', 'none');
            temperatureHandler.setUnvisible(map);
            legendArr.splice(legendArr.indexOf('temperature'), 1);
            updateLegend();
        }
    });
}

function initWinsButtonAction() {
    const winsButton = document.getElementById('wins-button');
    winsButton.addEventListener('click', () => {
        showStatus.wind = !showStatus.wind;
        winsButton.className = showStatus.wind ? 'weather-switch-selected' : 'weather-switch-not-selected';

        toggleButtonAction();
        if (showStatus.wind) {
            // legend.setData(windHandler.getLegendObj());
            // windHandler.updateChart();
            if (windHandler.getWindVelocityData().length == 0) {
                windHandler.loadWindVelocityData();
            } else {
                windHandler.onWindVelocityReRender();
            }
        } else {
            windHandler.onWindVelocityDestory();
        }
    });
}

function initRhButtonAction() {
    const rhButton = document.getElementById('rh-button');
    rhButton.addEventListener('click', () => {
        showStatus.seeing = !showStatus.seeing;
        rhButton.className = showStatus.seeing ? 'weather-switch-selected' : 'weather-switch-not-selected';

        toggleButtonAction();

        if (showStatus.seeing) {
            // map.setLayoutProperty('vism', 'visibility', 'visible');
            // legend.setData(rhHandler.getLegendObj());
            rhHandler.setVisible(map);
            legendArr.push('rh');
            updateLegend();
        } else {
            // map.setLayoutProperty('vism', 'visibility', 'none');
            rhHandler.setUnvisible(map);
            legendArr.splice(legendArr.indexOf('rh'), 1);
            updateLegend();
        }
    });
}

function initRainButtonAction() {
    const preButton = document.getElementById('pre-button');
    preButton.addEventListener('click', () => {
        showStatus.rain = !showStatus.rain;
        preButton.className = showStatus.rain ? 'weather-switch-selected' : 'weather-switch-not-selected';

        toggleButtonAction();
        if (showStatus.rain) {
            map.setLayoutProperty('pre', 'visibility', 'visible');
            // legend.setData(rainHandler.getLegendObj());
            // rainHandler.updateChart();
            legendArr.push('rain');
            updateLegend();
        } else {
            map.setLayoutProperty('pre', 'visibility', 'none');
            legendArr.splice(legendArr.indexOf('rain'), 1);
            updateLegend();
        }
    });
}

function initOdButtonAction() {
    const odButton = document.getElementById('od-button');
    odButton.addEventListener('click', () => {
        showStatus.od = !showStatus.od;
        odButton.className = showStatus.od ? 'weather-switch-selected' : 'weather-switch-not-selected';
        toggleButtonAction();
        if (showStatus.od) {
            odHandler.show(map);
        } else {
            odHandler.hide(map);
        }
    });
}

function toggleButtonAction() {
    if (showStatus.wind) {
        map.easeTo({
            pitch: 0,
            bearing: 0
        });
        map.dragRotate.disable();
    } else if (showStatus.rain) {
        map.easeTo({
            pitch: 60,
            bearing: 0
        });
        map.dragRotate.enable();
    } else {
        map.easeTo({
            pitch: 0,
            bearing: 0
        });
        map.dragRotate.enable();
    }
}

function updateLegend() {
    if (!legendArr.length) {
        legend.setData(null);
    } else {
        legend.setData(legendArrObj[legendArr[legendArr.length - 1]]);
    }
}

function initSignIn() {
    $('#sign-in').click((e) => {
        $('#sign-in-mask').css('display', 'block');
    });
    $('#sign-in-submit').click((e) => {
        e.preventDefault();
        if ($("#form-email").val() == 'admin' && 
            $("#form-password").val() == 'admin') {
            $('#sign-in-mask').css('display', 'none');
            $('#sign-up').css('display', 'none');
            $('#sign-in').css('display', 'none');
            $('#user-info').css('display', 'block');
            isSignIn = true;
            popupBox.show();
        } else {
            alert('账号密码错误！');
        }
    });
    $('#sign-up-submit').click((e) => {
        e.preventDefault();
    });
    $('#sign-in-close-button').click((e) => {
        e.preventDefault();
        $('#sign-in-mask').css('display', 'none');
    })
}

function initBoxControlButton() {
    const button = document.getElementById('box-control');
    button.addEventListener('click', (e) => {
        if (isBoxShow) {
            $('.octagon-bg-box-left').animate({
                left: '-215px'
            });
            $('.octagon-bg-box-right').animate({
                right: '-215px'
            });
            $('#incident-info').animate({
                left: '-440px'
            });
            $('#congestion-info').animate({
                left: '-440px'
            });
            $('#weather-info').animate({
                right: '-440px'
            });
            $('#road-weather-info').animate({
                right: '-440px'
            });
            $('.weather-switch').animate({
                left: '50px'
            });
            $('#legend').animate({
                left: '50px'
            });
            isBoxShow = false;
            document.getElementById('box-control-button-text').innerHTML = '显示窗口';
        } else {
            $('.octagon-bg-box-left').animate({
                left: '10px'
            });
            $('.octagon-bg-box-right').animate({
                right: '10px'
            });
            $('#incident-info').animate({
                left: '50px'
            });
            $('#congestion-info').animate({
                left: '50px'
            });
            $('#weather-info').animate({
                right: '50px'
            });
            $('#road-weather-info').animate({
                right: '50px'
            });
            $('.weather-switch').animate({
                left: '510px'
            });
            $('#legend').animate({
                left: '510px'
            });
            isBoxShow = true;
            document.getElementById('box-control-button-text').innerHTML = '隐藏窗口';
        }
    });
}